import {PlotTypes} from '../../enum/PlotTypes';
import {Point} from '../../type';


// @ts-ignore
export default class Rectangle extends ol.geom.Polygon {
    public params: any;
    public isPlot: boolean = true;
    public fixPointCount: number = 2;

    private readonly _type: PlotTypes;
    private points: Array<Point>;
    private isFill: boolean;

    constructor(coordinates: any, points: Array<Point>, params: any) {
        super([]);
        this._type = PlotTypes.POLYGON;
        this.points = [];
        this.isFill = ((params['isFill'] === false) ? params['isFill'] : true);
        if (points && points.length > 0) {
            this.setPoints(points);
        } else if (coordinates && coordinates.length > 0) {
            // @ts-ignore
            this.setCoordinates(coordinates);
        }
    }

    /**
     * 获取标绘类型
     * @return {PlotTypes}
     */
    public getPlotType(): PlotTypes {
        return this._type;
    }

    /**
     * 获取坐标点
     * @return {Array<Point>}
     */
    public getPoints(): Array<Point> {
        return this.points.slice(0);
    }

    /**
     * 获取点数理
     * @return {number}
     */
    public getPointCount(): number {
        return this.points.length;
    }

    /**
     * 更新当前坐标
     * @param point
     * @param index
     */
    public updatePoint(point: Point, index: number): void {
        if (index >= 0 && index < this.points.length) {
            this.points[index] = point;
            this.generate();
        }
    }

    /**
     * 更新最后一个坐标
     * @param point
     * @private
     */
    private updateLastPoint(point: Point): void {
        this.updatePoint(point, this.points.length - 1);
    }

    /**
     * 完成绘制
     */
    public finishDrawing(): void {

    }

    private setPoints(value: Array<Point>): void {
        this.points = !value ? [] : value;
        if (this.points.length >= 1) {
            this.generate();
        }
    }

    private generate(): void {
        if (this.points.length === 2) {
            let coordinates: Array<Point> = [];
            if (this.isFill) {
                // @ts-ignore
                let extent: any = ol.extent.boundingExtent(this.points);
                // @ts-ignore
                let polygon: any = ol.geom.Polygon.fromExtent(extent);
                coordinates = polygon.getCoordinates();
            } else {
                let start: Point = this.points[0];
                let end: Point = this.points[1];
                coordinates = [start, [start[0], end[1]], end, [end[0], start[1]], start];
            }
            // @ts-ignore
            this.setCoordinates(coordinates);
        }
    }
}